package com.oros.utils;
import com.vaadin.Application;
import java.io.*;

import java.security.Principal;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.vaadin.service.ApplicationContext;
import com.vaadin.service.ApplicationContext.TransactionListener;

public class GAERegistration implements Serializable {
 
	private static final long serialVersionUID = 401772299029612443L;
	private RegistrationUnit regunit;
	private boolean userInitCompleted=false;
	public GAERegistration(RegistrationUnit regunit)
	{
		this.regunit = regunit;
	}
	private static HashMap<ApplicationContext, TransactionListener> requestListeners = new HashMap<ApplicationContext, TransactionListener>();

	private boolean isInitialized = false;
	public void init() {
		// Only add one listener per context as Vaadin calls every listener in
		// the context for every request.
        Application application  = regunit.getApplication();		
		if (application.getContext() != null && requestListeners.get(application.getContext()) == null) {
			TransactionListener listener = new TransactionListener() {
				private static final long serialVersionUID = -8490216576436646032L;

				@Override
				public void transactionStart(Application app, Object req) {
					
					if (!isInitialized) {
						    regunit.minimum_initMainAppForm(); 
						isInitialized = true;
						}	
					checkLoginLogout((HttpServletRequest) req);
				}

				@Override
				public void transactionEnd(Application app, Object req) {
					// NOP
				}
			};

			application.getContext().addTransactionListener(listener);

			requestListeners.put(application.getContext(), listener);
		}
	}
	private void checkLoginLogout(HttpServletRequest request) 
	{
	
		Principal user = request.getUserPrincipal();
        Application application = regunit.getApplication();
		if (regunit.isAuthetincationFormAlreadyBuilt()
				&& ((user != null && application.getUser() != null && userInitCompleted) || (user == null && 
				application.getUser() == null))) {
			return; // Layout initialized, and no login/logout detected
		}
		userInitCompleted=false;
		UserService userService = UserServiceFactory.getUserService();

		if (request.getUserPrincipal() != null) {
			// Login detected, store user email to application
			String userName=request.getUserPrincipal().getName();
			application.setUser(userName);
            boolean isInternalUserAdmin= userService.isUserAdmin();
            String logoutURL = userService
    				.createLogoutURL(request.getRequestURI());
            regunit.showFormForRegisteredUser(userName, userName, isInternalUserAdmin, logoutURL);
            userInitCompleted=true;
         /*******************************************************/
			//mainWindow.showNotification("Hello "+ request.getUserPrincipal().getName());

		/*********************************************/			
		} else {
			Object recentUser =application.getUser();
			application.setUser(null);
			String loginURL= userService.createLoginURL(request.getRequestURI());
			regunit.showFormForUnregisteredUser(recentUser==null?null:recentUser.toString(),loginURL);
			// Logout detected, or application initialized without login info
		}

	}	
}
